import axios from 'axios'
import storage from 'store'
import { TOKEN_KEY } from './constants'
import { ElMessage } from 'element-plus'

const request = axios.create({
	baseURL: import.meta.env.APP_BASE_URL,
	timeout: 6000
})
const errorHandler = (error) => {
	console.log("errorHandler",error)
	if(error.response){
		const data = error.response.data
		console.log("errorHandler",error.response)
		if (error.response.status !== 200) {
			ElMessage.error(data.msg?data.msg : error.response.statusText)
		}
	}
	return Promise.reject(error)
}

request.interceptors.request.use(config => {
	let token =  undefined
	if(storage.get('rememberMe')){
		token = storage.get(TOKEN_KEY)
	}else{
		token = JSON.parse(sessionStorage.getItem(TOKEN_KEY))
	}
	 
	  // 如果 token 存在
	  // 让每个请求携带自定义 token 请根据实际情况自行修改
	  if (token) {
	    config.headers[TOKEN_KEY] = token.token
	  }
	  return config
}, errorHandler)

request.interceptors.response.use(response => {
	if(response.data instanceof ArrayBuffer){ // 文件流直接返回response
		return response
	}
	return response.data
}, errorHandler)

export default request
